package cn.sdormitory.school.service.impl;

import cn.sdormitory.basedata.dao.BClassDao;
import cn.sdormitory.basedata.dao.BDormitoryDao;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.entity.BClass;
import cn.sdormitory.basedata.entity.BDormitory;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.basedata.vo.BClassVo;
import cn.sdormitory.basedata.vo.BDormitoryVO;
import cn.sdormitory.common.api.CommonPage;
import cn.sdormitory.common.exception.ApiException;
import cn.sdormitory.common.sms.TxSmsTemplate;
import cn.sdormitory.school.dao.SchoolPatrolDao;
import cn.sdormitory.school.dao.SchoolPatrolHandleDao;
import cn.sdormitory.school.entity.SchoolPatrol;
import cn.sdormitory.school.entity.SchoolPatrolHandle;
import cn.sdormitory.school.service.SchoolPatrolService;
import cn.sdormitory.sys.dao.SysDictDetailDao;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.dao.SysUserRoleDao;
import cn.sdormitory.sys.entity.SysDictDetail;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.sys.entity.SysUserRole;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

@Service("schoolPatrolService")
@Slf4j
public class SchoolPatrolServiceImpl extends ServiceImpl<SchoolPatrolDao, SchoolPatrol> implements SchoolPatrolService {

    @Autowired
    private SchoolPatrolDao schoolPatrolDao;

    @Autowired
    private SchoolPatrolHandleDao schoolPatrolHandleDao;

    @Autowired
    private BClassDao bClassDao;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private BDormitoryDao bDormitoryDao;

    @Autowired
    private BStudentDao bStudentDao;

    @Autowired
    private SysDictDetailDao sysDictDetailDao;

    @Autowired
    private TxSmsTemplate txSmsTemplate;

    @Override
    public CommonPage<SchoolPatrol> getPage(Map<String, Object> params) {
        int pageSize = Integer.parseInt(String.valueOf(params.get("pageSize")));
        int pageNum = Integer.parseInt(String.valueOf(params.get("pageNum")));

        List<SchoolPatrol> list = this.schoolPatrolDao.getSchoolPatrolList(params, (pageNum - 1) * pageSize, pageSize);

        CommonPage commonPage = CommonPage.getCommonPage(pageNum, pageSize, this.schoolPatrolDao.getSchoolPatrolListCount(params), list);

        return commonPage;
    }

    @Override
    public int createOrUpdatePatrolInfo(SchoolPatrol schoolPatrol) {
        int num=0;
        if(StringUtils.isEmpty(schoolPatrol.getId())){
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = format.format(new Date());
            num = schoolPatrolDao.insert(schoolPatrol);

            //是否进行通知
            if("1".equals(schoolPatrol.getIsInformCharge())){
                //短信参数
                String mobile = "";
                StringBuilder smsContent = new StringBuilder();

                //值班处理待办
                SchoolPatrolHandle schoolPatrolHandle = new SchoolPatrolHandle();
                schoolPatrolHandle.setPatrolId(schoolPatrol.getId());

                //宿舍
                if( "1".equals(schoolPatrol.getPatrolType())){
                    //获取具体违纪情况内容（格式：明志楼-201）
                    String dormitoryId = schoolPatrol.getDormitoryId();
                    BDormitory bDormitory = bDormitoryDao.selectById(dormitoryId);

                    QueryWrapper<SysDictDetail> sysDictDetailWrapper = new QueryWrapper<>();
                    sysDictDetailWrapper.eq("dict_type","sys_building")
                            .eq("dict_value",bDormitory.getBuildingNo());
                    SysDictDetail sysDictDetail = sysDictDetailDao.selectOne(sysDictDetailWrapper);

                    smsContent.append(sysDictDetail.getDictLabel()).append("-").append(bDormitory.getDormitoryNo());

                    if(bDormitory.getDormitoryTeacherId() == null){
                        throw new ApiException("当前宿舍无负责人");
                    }else {
                        SysUser user = sysUserDao.selectById(bDormitory.getDormitoryTeacherId());
                        mobile = user.getPhone();
                        schoolPatrolHandle.setChargeTeacherId(user.getId());
                    }
                    String[] params = {smsContent.toString()};
                    schoolPatrolHandle.setSmsParams(smsContent.toString());
                    String dormResult = txSmsTemplate.sendMesModel(mobile, params,1);

                    if("OK".equals(dormResult)){
                        schoolPatrolHandle.setSmsStatus("0");
                    }else {
                        schoolPatrolHandle.setSmsStatus("1");
                    }
                    //发送短信给部门经理
                    List<SysUser> deptManagerList = sysUserDao.getDeptManagerSysUserByDept("后勤部");
                    Random r = new Random();
                    int index = r.nextInt(deptManagerList.size());
                    txSmsTemplate.sendMesModel(deptManagerList.get(index).getPhone(),params,2);
                }else{
                    //获取具体违纪情况内容（格式：班级-学生姓名）
                    BClass bClass = bClassDao.selectById(schoolPatrol.getClassId());
                    smsContent.append(bClass.getClassName());
                    //是否具体到学生个人
                    if(!StringUtils.isEmpty(schoolPatrol.getStudentNo())){
                        QueryWrapper<BStudent> stuWrapper = new QueryWrapper<>();
                        stuWrapper.eq("student_no",schoolPatrol.getStudentNo());
                        BStudent bStudent = bStudentDao.selectOne(stuWrapper);
                        smsContent.append("-").append(bStudent.getStudentName());
                    }

                    SysUser sysUser = sysUserDao.selectById(bClass.getClassTeacherId());
                    schoolPatrolHandle.setChargeTeacherId(sysUser.getId());

                    mobile = sysUser.getPhone();
                    String[] params = {smsContent.toString()};
                    schoolPatrolHandle.setSmsParams(smsContent.toString());

                    String schoolResult = txSmsTemplate.sendMesModel(mobile, params,1);
                    if("OK".equals(schoolResult)){
                        schoolPatrolHandle.setSmsStatus("0");
                    }else {
                        schoolPatrolHandle.setSmsStatus("1");
                    }

                    QueryWrapper<SysDictDetail> wrapper = new QueryWrapper<>();
                    wrapper.eq("dict_type","class_dept").eq("dict_value",bClass.getClassDept());
                    SysDictDetail sysDictDetail = sysDictDetailDao.selectOne(wrapper);
                    String classDept = sysDictDetail.getDictLabel();

                    //发送短信给部门经理
                    if("启蒙星".equals(classDept)){
                        QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
                        userWrapper.eq("username","李琴辉");
                        SysUser deptManager = sysUserDao.selectOne(userWrapper);
                        if(deptManager != null){
                            txSmsTemplate.sendMesModel(deptManager.getPhone(),params,2);

                        }
                    }else if("BCSP".equals(classDept)){
                        QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
                        userWrapper.eq("username","汤金霞");
                        SysUser deptManager = sysUserDao.selectOne(userWrapper);
                        if(sysUser != null){
                            txSmsTemplate.sendMesModel(deptManager.getPhone(),params,2);
                        }
                    }else if("实训部".equals(classDept)){
                        QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
                        userWrapper.eq("username","黄群英");
                        SysUser deptManager = sysUserDao.selectOne(userWrapper);
                        if(deptManager != null){
                            txSmsTemplate.sendMesModel(deptManager.getPhone(),params,2);
                        }
                    }
                }
                schoolPatrolHandle.setHandleStatus("0");
                schoolPatrolHandle.setCreateDate(currentTime);
                schoolPatrolHandleDao.insert(schoolPatrolHandle);
            }
        }else{
            num = schoolPatrolDao.updateById(schoolPatrol);
        }
        return num;
    }

    @Override
    public int deletePatrolInfo(Long id) {
        return schoolPatrolDao.deleteById(id);
    }

    @Override
    public List<BClassVo> getClassListByDept(String dutyDept) {
        if("1".equals(dutyDept)){
            String depts[] = {"0","1"};
            return schoolPatrolDao.getClassListByDept(depts);
        }else{
            String depts[] = {"2", "3", "4"};
            return schoolPatrolDao.getClassListByDept(depts);
        }

    }

    @Override
    public List<BDormitoryVO> getDormitoryNameByName(String name) {
        return schoolPatrolDao.getDormitoryNameByName(name);
    }

    @Override
    public SchoolPatrol getSchoolPatrolDetails(Long id) {
        Map<String,Object> params = new HashMap<>();
        params.put("id",id);
        List<SchoolPatrol> list = this.schoolPatrolDao.getSchoolPatrolList(params, 0, 1);
        if(list!=null && list.size()>0){
            return list.get(0);
        }else{
            return null;
        }

    }
}
